package com.example.netty.callback;

import com.example.netty.service.TerminalContext;
import com.example.netty.service.TerminalContextService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

/**
 * @Auther Created by l.wang on 2019/5/29.
 */
@Component
public class LongConnectEventCallback implements SampleLongConnectEventCallback {
    private static Log log = LogFactory.getLog(LongConnectEventCallback.class);

    private final TerminalContextService terminalContextService;

    public LongConnectEventCallback(TerminalContextService terminalContextService) {
        this.terminalContextService = terminalContextService;
    }

    @Override
    public void onConnectionCreated(ChannelHandlerContext channelHandlerContext) {
        terminalContextService.onConnect(channelHandlerContext);
    }

    @Override
    public void onConnectionClosed(ChannelHandlerContext channelHandlerContext) {
        try {
            TerminalContext terminalContext = terminalContextService.onDisconnect(channelHandlerContext);
            log.info("Connection closed sessionId:" + terminalContext.getSessionId() + "Tid:" + terminalContext.getTid());
        } catch (Exception e) {
//            log.error(Throwables.getStackTraceAsString(e));
        }
    }

    @Override
    public void onConnectionIdle(IdleState idleState, ChannelHandlerContext channelHandlerContext) {
        if (idleState == IdleState.READER_IDLE || idleState == IdleState.WRITER_IDLE || idleState == IdleState.ALL_IDLE) {
            channelHandlerContext.close();
        }
    }

    @Override
    public void onRead(ChannelHandlerContext channelHandlerContext, Object msg) {
        terminalContextService.channelRead(channelHandlerContext, msg);
    }
}